package com.example.test02mybatisplus.interceptor;

import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Properties;

/**
 * @Author: fxy
 * @Date: 2022/04/14/13:41
 * @Description:
 */
@Intercepts({@Signature(type = Executor.class, method = "query",
        args = {MappedStatement.class,
                Object.class,
                RowBounds.class,
                ResultHandler.class})})
public class MySqlInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        invocation.getMethod();
        MappedStatement ms = (MappedStatement) args[0];
        // 获取执行的该拦截器的全路径方法 比如你的 UserInfoMapper 接口的 getById 方法， com.xx.UserInfoMapper.getById
        String id = ms.getId();
        // 如果不是 searchByQuery 方法，就不进行相关的拦截操作
        if (!filterMethodById(id)){
            return invocation.proceed();
        }
        // 该参数类型 org.apache.ibatis.binding.MapperMethod$ParamMap
        Object parameterObject = args[1];

        // 获取传递的参数， 主要包含三个参数 1. 查询语句 searchQuery， 2. 查询偏移 pageOffset, 3. 查询每页的数据条数
        MapperMethod.ParamMap paramMap = (MapperMethod.ParamMap) parameterObject;

        // 对查询的条件进行重新拼接
        // searchQuery 查询的条件
        String searchQuery = "";
        // pageOffset 分页查询的偏移
        int pageOffset = 0 ;
        // pageSize 分页查询页面大小，即每页多少条数据
        int pageSize = 10;
        // 取出各个参数并赋值
        if (paramMap.containsKey("searchQuery")){
            searchQuery = (String) paramMap.get("searchQuery");
        }
        if (paramMap.containsKey("pageOffset")){
            pageOffset = (int) paramMap.get("pageOffset");
        }
        if (paramMap.containsKey("pageSize")){
            pageSize = (int) paramMap.get("pageSize");
        }

        BoundSql boundSql = ms.getBoundSql(parameterObject);
        // 获取原始查询的 sql 语句
        String origSql = boundSql.getSql();
     
        // 构建新的 sql 语句， 将 where 条件和 limit 条件加入
        String newSql = null;
        // 如果存在条件查询则 拼接条件，如果不存在，则只添加分页限制
        if (!searchQuery.equals("")){
            newSql =  origSql +" WHERE " + searchQuery + " LIMIT " + pageSize + " OFFSET " + pageOffset;
        }else {
            newSql = origSql + " LIMIT " + pageSize + " OFFSET " + pageOffset;
        }

        // 重新new一个查询语句对象
        BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql,
                boundSql.getParameterMappings(), boundSql.getParameterObject());

        // 把新的查询放到 statement 里
        MappedStatement newMs = newMappedStatement(ms, new MySqlInterceptor.BoundSqlSqlSource(newBoundSql));
        for (ParameterMapping mapping : boundSql.getParameterMappings()) {
            String prop = mapping.getProperty();
            if (boundSql.hasAdditionalParameter(prop)) {
                newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
            }
        }

        // 修改 MappedStatement
        Object[] queryArgs = invocation.getArgs();
        queryArgs[0] = newMs;
       
        return invocation.proceed();
        
    }

    class BoundSqlSqlSource implements SqlSource {
        private BoundSql boundSql;
        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }
        @Override
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }

    }

    private boolean filterMethodById(String id){
        System.out.println("id: " + id);
        String[] names = id.split("\\.");
        System.out.println("names: " + names.length);
        return names[names.length - 1].equals("selectList");
    }

    private MappedStatement newMappedStatement (MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new
                MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
            builder.keyProperty(ms.getKeyProperties()[0]);
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }

    @Override
    public void setProperties(Properties properties) {
        // 获取属性
        // String value1 = properties.getProperty("prop1");
    }

}
